import React, { useEffect, useState } from 'react';
import ContentCard from '../../../components/ContentCard';
import Button from '@knownsec/react-component/dist/Button';
import Message from '@knownsec/react-component/dist/Message';
import Input from '@knownsec/react-component/dist/Input';
import Icon from '@knownsec/react-component/dist/Icon';
import Table from '@knownsec/react-component/dist/Table';
import Tooltip from '@knownsec/react-component/dist/Tooltip';
import Confirm from '@knownsec/react-component/dist/Confirm';
import Dialog from '@knownsec/react-component/dist/Dialog';
import Pagination from '@knownsec/react-component/dist/Pagination';
import CopyBoard from '../../../components/CopyBoard';
import { turnToUrlparam } from '../../../helpers/getUrlParams';
import EmptyData from '../../../components/empty/EmptyData';
import fetchFer from 'API/fetch';
import { Link } from 'react-router-dom';
import cn from 'classnames';
import s from './style.module.css';
import Select, { Option } from '@kuiper-components/select';

function vulTempSettings() {
	const SCENE_OPTIONS = [
		{
			name: 'Web监测',
			value: 'web',
		},
		{
			name: '主机监测',
			value: 'host',
		},
		{
			name: 'Web、主机监测',
			value: 'multiple',
		},
	];
	const columns = [
		{
			title: '模板名称',
			dataIndex: 'display_name',
			render({ zh_cn }) {
				return <CopyBoard text={zh_cn} className={s.db} maxWidth="11rem" />;
			},
		},
		{
			title: '含插件数',
			dataIndex: 'plugins_count',
		},
		{
			title: '严重',
			dataIndex: 'plugin_severity',
			render(e) {
				return e ? e['5'] || 0 : 0;
			},
		},
		{
			title: '高危',
			dataIndex: 'plugin_severity',
			render(e) {
				return e ? e['4'] || 0 : 0;
			},
		},
		{
			title: '中危',
			dataIndex: 'plugin_severity',
			render(e) {
				return e ? e['3'] || 0 : 0;
			},
		},
		{
			title: '低危',
			dataIndex: 'plugin_severity',
			render(e) {
				return e ? e['2'] || 0 : 0;
			},
		},
		{
			title: '监测场景',
			// dataIndex: 'plugin_severity',
			// render(e) {
			// 	return e ? e['2'] || 0 : 0;
			// },
		},
		{
			title: '描述',
			dataIndex: 'description',
			render(e) {
				return e ? (
					<Tooltip
						placement="topLeft"
						overlay={<div className={s.maxW300}>{e}</div>}
					>
						<div className="ell">{e}</div>
					</Tooltip>
				) : (
					'- -'
				);
			},
		},
		{
			title: '操作',
			dataIndex: 'detail',
			width: 140,
			render(e, row) {
				return (
					<>
						<Button
							type="text"
							className={s.p0}
							onClick={() => setVisible(row)}
						>
							查看
						</Button>
						{row?.custom_profile_template_id && (
							<>
								<Link
									to={`/policy-manage/vul-template-settings/create?custom_profile_template_id=${row.custom_profile_template_id}`}
								>
									<Button type="text" className={cn(s.p0, 'ml10 mr10')}>
										编辑
									</Button>
								</Link>
								<Button
									type="text"
									className={s.p0}
									onClick={() =>
										deleteTemplate([row.custom_profile_template_id])
									}
								>
									删除
								</Button>
							</>
						)}
					</>
				);
			},
		},
	];
	const [data, setData] = useState([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState([]);
	const onSelectChange = newSelectedRowKeys => {
		setSelectedRowKeys(newSelectedRowKeys);
	};
	const [filter, setFilter] = useState({
		page: 1,
		limit: 10,
		name: '',
		scene_type: 'web',
	});

	const handleReSet = () => {};
	const [name, setName] = useState('');
	const [total, setTotal] = useState(1);
	const [visible, setVisible] = useState('');
	const deleteTemplate = ids => {
		Confirm({
			pro: true,
			className: s.w350,
			message: (
				<div className={cn('mb10 pt0 pb0 pl20 pr20')}>
					<Icon type="error" className={cn('warning-color fs24 mb10 db tac')} />
					<div className="tac">确认要删除选中的模版吗？</div>
				</div>
			),
			onconfirm: async () => {
				const res = await fetchFer(`/api/v2/kb/deleted_profile`, {
					method: 'POST',
					body: JSON.stringify({ custom_profile_template_ids: ids }),
					checkStatus: 501,
				}).catch(err => {
					return err;
				});
				if (res.code === 200) {
					Message.show({ type: 'success', message: '操作成功' });
					setTimeout(() => getVulTempList(), 0);
				} else {
					Message.show({ type: 'error', message: '操作失败' });
				}
			},
			oncancel: () => {},
		});
	};
	const checkCount = async () => {
		const res = await fetchFer(`/api/v2/kb/custom_profile_count`, {
			method: 'GET',
			checkStatus: 501,
		}).catch(err => {
			return err;
		});
		if (res.msg === 'ok') {
			if (res.data.custom_profile_count >= 100) {
				Message.show({
					type: 'warning',
					message: '系统最多可添加100条漏洞检测模板。',
				});
			} else {
				window.location.href = '/#/policy-manage/vul-template-settings/create';
			}
		}
	};
	const [loading, setLoading] = useState(false);
	const getVulTempList = async () => {
		setLoading(true);
		setData([]);
		const params = turnToUrlparam(filter);
		const res = await fetchFer(`/api/v2/kb/get_profile?${params}`, {
			method: 'GET',
			checkStatus: 501,
		}).catch(err => {
			return err;
		});
		if (res.code === 200) {
			const resData = res.data.templates.map((item, k) => {
				item.key = item.custom_profile_template_id;
				return item;
			});
			setData(resData);
			setTotal(res.data.total);
		}
		setLoading(false);
	};
	useEffect(() => {
		getVulTempList();
	}, [filter]);
	return (
		<ContentCard
			bread={{
				arr: [
					{ link: '', name: '综合管理' },
					{ link: '', name: '漏洞模板', active: true },
				],
			}}
			content={
				<div className="p20">
					<div style={{ marginBottom: '10px' }}>
						<Button type="primary" onClick={checkCount}>
							新增模板
						</Button>
					</div>
					<div className="df aic jcsb">
						<Input
							placeholder="请输入漏洞模板名称"
							value={name}
							onChange={({ value }) => setName(value.trim())}
							onSearch={({ value }) =>
								setFilter({ ...filter, page: 1, name: value.trim() })
							}
							search
							className={s.w240}
						/>
						<div>
							<Select
								placeholder="监测场景"
								className={s.item}
								// value={filter?.scene_type}
								// onChange={taskTriggerType => reSearch({ taskTriggerType })}
								// getPopupContainer={getDropdownRef}
							>
								{SCENE_OPTIONS.map(({ name, value }) => (
									<Option key={value} value={value}>
										{name}
									</Option>
								))}
							</Select>
							<Button type="primary" onClick={handleReSet}>
								重置
							</Button>
						</div>
					</div>
					<Table
						pro
						loading={loading}
						className={cn(s.smallTable, 'mt16')}
						columns={columns}
						empty={<EmptyData borderless={true} />}
						rowSelection={{
							width: 50,
							selectedRowKeys,
							onChange: onSelectChange,
							getCheckboxProps: record => ({
								disabled: !record.key,
							}),
						}}
						data={data}
					/>
					<div className="df aic jcsb mt10">
						<Button
							className={s.p0}
							onClick={() => deleteTemplate(selectedRowKeys)}
							type="text"
							disabled={selectedRowKeys.length === 0}
						>
							批量删除
						</Button>
						{total > 10 && (
							<Pagination
								current={filter?.page}
								pageSize={filter?.limit}
								showQuickJumper={{ goButton: true }}
								showSizeChanger={true}
								showTotal={total => `共${total}条`}
								pageSizeOptions={['10', '20', '50']}
								total={total}
								onChange={(page, limit) =>
									setFilter({ ...filter, page, limit })
								}
							/>
						)}
					</div>
					{/* 查看 */}
					<Dialog
						className={cn(s.moduleDialog2, s.w840)}
						title="查看详情"
						maskClosable={true}
						cancelText=""
						confirmText="关闭"
						onsubmit={() => setVisible('')}
						onhide={() => {
							setVisible('');
						}}
						visible={visible}
					>
						<div className={cn(s.p24)}>
							<table className={cn(s.diaTab, 'w100p')}>
								<tr>
									<td className={s.keyTd}>模版名称</td>
									<td>{visible?.display_name?.zh_cn || ''}</td>
								</tr>
								<tr>
									<td className={s.keyTd}>含插件数</td>
									<td>{visible?.plugins_count}</td>
								</tr>{' '}
								<tr>
									<td className={s.keyTd}>插件详情</td>
									<td className={s.keyDet}>
										<div className={s.detailTD}>
											{visible &&
												Object.entries(visible?.plugin_types).map(
													([key, val]) => {
														return (
															<>
																<p className={s.detailP}>
																	<span>{key} </span>
																</p>
																<div className={s.detailD}>
																	{val.map((e, i) => {
																		return (
																			<span className={s.detailSpan} title={e}>
																				{e}
																			</span>
																		);
																	})}
																	{val.length % 2 !== 0 && (
																		<span
																			className={s.detailSpan}
																			title={s.detail}
																		></span>
																	)}
																</div>
																<p style={{ height: '2rem' }}></p>
															</>
														);
													}
												)}
										</div>
									</td>
								</tr>
							</table>
						</div>
					</Dialog>
				</div>
			}
		/>
	);
}

export default vulTempSettings;
